package com.supreme.threadserver.threadpkg;

import java.util.concurrent.TimeUnit;

public class LoopLocalThread implements Runnable {

    private static final ThreadLocal<Integer> loopThreadLocal = ThreadLocal.withInitial(() -> 100);

    private final int loopCount;

    private final int waitingTime;

    public LoopLocalThread() {
        this.loopCount = 10;
        this.waitingTime = 1000;
    }

    public LoopLocalThread(int loopCount, int waitingTime) {
        this.loopCount = loopCount;
        this.waitingTime = waitingTime;
    }

    @Override
    public void run() {
        final Thread currentThread = Thread.currentThread();
        final String threadName = currentThread.getName();
        final long threadId = currentThread.getId();
        for (int i = 0; i < this.loopCount; i++) {
            try {
                TimeUnit.MILLISECONDS.sleep(this.waitingTime);
                Integer localValue = loopThreadLocal.get();
                loopThreadLocal.set(999);
                Integer newLocalValue = loopThreadLocal.get();
                System.out.printf("[NAME: %s ID: %d] index: %d localValue: %d newLocalValue: %d\n", threadName, threadId, i, localValue, newLocalValue);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
